package threads;
/**线程之间交换数据例子*/
import java.util.Scanner;
import java.util.concurrent.Exchanger;
public class ExchangerExample {
    public static void main(String[] args)throws InterruptedException
    {
        Exchanger<String> exchanger=new Exchanger<>();//使用泛型定义类型
        BackgroundWorker worker=new BackgroundWorker(exchanger);
        new Thread(worker).start();
        Scanner scanner=new Scanner(System.in);
        while(true)
        {
            System.out.println("请输入要查询的学生的姓名：");
            String input=scanner.nextLine().trim();
            exchanger.exchange(input);//把输入的传递给线程
            String value=exchanger.exchange(null);//拿到线程反馈结果
            if ("exit".equals(value))
            {
                break;
            }
            System.out.println("查询结果："+value);
        }
        scanner.close();
    }
}
class BackgroundWorker implements Runnable
{
        final Exchanger<String> exchanger;
        //构造函数优先
        BackgroundWorker(Exchanger<String>exchanger)
        {
            this.exchanger=exchanger;
        }
        public void run()
        {
            while(true)
            {

                try {
                    String item=exchanger.exchange(null);
                    switch(item)
                    {
                        case "zhangsan":
                            exchanger.exchange("90");
                            break;
                        case "lisi":
                            exchanger.exchange("80");
                            break;
                        case "wangwu":
                            exchanger.exchange("70");
                            break;
                        case "exit":
                            exchanger.exchange("exit");
                            return;
                        default:
                           exchanger.exchange("查无此人");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

}
